package com.zhugang.week04;

/**
 * @program algorithms
 * @description: insertSort
 * @author: chanzhugang
 * @create: 2022/06/27 10:21
 */
public class InsertSort3 {

    public static void main(String[] args) {
        InsertSort3 insertSort3 = new InsertSort3();
        int[] a = new int[]{6, 4, 5, 1, 2, 3};
        insertSort3.insertSort(a, a.length);
        for (int i : a) {
            System.out.println(i);
        }
    }

    /**
     * 插入排序
     *
     * @param a
     * @param n
     */
    public void insertSort(int[] a, int n) {
        // 已排序区间 - 未排序区间（取值往已排序区间中插入）
        for (int i = 1; i < n; i++) {
            int val = a[i];
            int j = i - 1;
            for (; j >= 0; j--) {
                if (a[j] > val) {
                    a[j + 1] = a[j];
                } else {
                    break;
                }
            }
            a[j + 1] = val;
        }
    }
}